﻿#include "as_mysql_result.h"
#include <mysql.h>
#include <algorithm>

as::db::MysqlResult::MysqlResult(MYSQL_RES* res)
{
	SetRes(res);
}

as::db::MysqlResult::~MysqlResult()
{
	if (result_)
	{
		mysql_free_result(result_);
	}
}

#include <iostream>
void as::db::MysqlResult::SetRes(MYSQL_RES* res)
{
	result_ = res;
	keyToVal_.clear();
	if (result_)
	{
		field_ = mysql_fetch_field(result_);
		field_num_ = mysql_num_fields(result_);
		MYSQL_ROW row;
		while (row = mysql_fetch_row(result_))
		{
			for (int i = 0; i < field_num_; ++i)
			{
				std::string sk(field_[i].name);
				std::for_each(sk.begin(), sk.end(), [](char& c) { c = std::tolower(c); });
				keyToVal_[sk].push_back((char*)row[i]);
			}
		}
	}
	else
	{
		field_ = nullptr;
		field_num_ = 0;
	}
}

int as::db::MysqlResult::GetFiledNum()
{
	return field_num_;
}

std::vector<char*> as::db::MysqlResult::GetVal(const char* key)
{
	std::string sk(key);
	std::for_each(sk.begin(), sk.end(), [](char& c) { c = std::tolower(c); });
	auto it = keyToVal_.find(sk);
	if (it == keyToVal_.end())
		return {};
	return it->second;
}

as::db::MysqlResult* as::db::MysqlResult::operator=(const MysqlResult* r)
{
	result_ = r->result_;
	field_ = r->field_;
	field_num_ = r->field_num_;
	return this;
}

